package tonytech.wordcode.service;


import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by hkl
 * 文档写入服务类
 */
public class DocWriterService implements DocWriterServiceImpl {
    private final XWPFDocument document ;
    private final File fileToStore;
    DocWriterService(File file) {
        document = new XWPFDocument();
        fileToStore = file;
    }

    @Override
    public void writeWord(String line) {
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setIndentationLeft(0);
        paragraph.setIndentationHanging(0);
        paragraph.setAlignment(ParagraphAlignment.LEFT);
        paragraph.setWordWrap(true);
        //在段落中新插入一个run,这里的run我理解就是一个word文档需要显示的个体,里面可以放文字,参数0代表在段落的最前面插入
        XWPFRun run = paragraph.createRun();
        //设置run内容
        run.setText(line);
        run.setFontFamily("宋体");
        run.setBold(true);
    }

    @Override
    public void closeDoc() {
        File newFile = null;
        FileOutputStream fos = null;
        try {
            newFile = new File("~tmp.docx");
            fos = new FileOutputStream(newFile);
            document.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos!=null){
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            newFile.renameTo(fileToStore);
        }


    }
}
